import UserImformation.Account;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

@WebServlet("/ChangeHeadImgServlet")
public class ChangeHeadImgServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Map<String,String> infoMap = (Map<String, String>) req.getSession().getAttribute("user");
        String username = infoMap.get("username");
        File file = new File("UserInfo.txt");
        Account account = new Account();

        int n = 0;
        int len = 0;
        Account[] users;

        Reader reader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            if (!str.trim().equals("")) {
                n++;
            }
        }
        bufferedReader.close();
        reader.close();

        if (n != 0) {
            users = new Account[n];
            Jsonb jsonb = JsonbBuilder.create();
            reader = new FileReader(file);
            bufferedReader = new BufferedReader(reader);
            while ((str = bufferedReader.readLine()) != null) {
                if (!str.trim().equals("")) {
                    users[len++] = jsonb.fromJson(str, Account.class);
                }
            }
            bufferedReader.close();
            reader.close();

            if(users!=null) {
                for (int i = 0; i < users.length; i++) {
                    if (users[i].getUsername().equals(username)) {
                        account = users[i];
                        break;
                    }
                }

                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload;
                upload = new ServletFileUpload(factory);
                List<FileItem> list = null;
                String head_img = null;
                try {
                    list = upload.parseRequest(req);
                    for (FileItem fi : list) {
                        if (!fi.isFormField()) {
                            if (fi.getSize() != 0) {
                                head_img = fi.getName();
                                String path = getServletContext().getRealPath("/headImages");
                                InputStream is = fi.getInputStream();
                                FileOutputStream os = new FileOutputStream(new File(path, head_img));
                                IOUtils.copy(is, os);
                                os.close();
                                is.close();
                                fi.delete();
                            }
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }

                account.setImg(head_img);

                len = 0;
                jsonb = JsonbBuilder.create();
                reader = new FileReader(file);
                bufferedReader = new BufferedReader(reader);
                while ((str = bufferedReader.readLine()) != null) {
                    if(!str.trim().equals("")){
                        users[len++] = jsonb.fromJson(str,Account.class);
                    }
                }
                bufferedReader.close();
                reader.close();

                StringBuffer bu = new StringBuffer();
                BufferedWriter out = null;
                jsonb = JsonbBuilder.create();
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false)));

                for (int i = 0; i < users.length; i++) {
                    if (users[i].getUsername()!=null) {
                        if (users[i].getUsername().equals(account.getUsername())) {
                            users[i] = account;
                        }
                        String infoJson = jsonb.toJson(users[i]);
                        bu.append(infoJson + "\n");
                    }
                }
                String userString = bu.toString();
                out.write(userString);
                out.close();
                resp.sendRedirect("/user.jsp");
            }
        }
    }
}
